/*
 * @Author: Hunter
 * @Date: 2022-03-12 13:48:04
 * @LastEditTime: 2022-03-12 14:39:53
 * @LastEditors: Hunter
 * @Description: 
 * @FilePath: \book-mark-client\src\utils\html.ts
 * 可以输入预定的版权声明、个性签名、空行等
 */

import cheerio, { Cheerio } from 'cheerio'
import { File, Folder } from "@/layout/menu/types";
export declare interface IHTMLSystem {
    count: number
    resetCount: () => void
    initHTML: (html: string) => Array<Folder | File>
    getChildrenNode: (node: Cheerio<any>, bookMarks: Array<Folder | File>) => void
    getNodeTitle: (node: Cheerio<any>) => void
    getNodeInfo: (node: Cheerio<any>, info: Folder | File) => File
}
export class HTMLSystem implements IHTMLSystem {
    count = 0
    resetCount = () => {
        this.count = 0;
    };
    initHTML(html: string) {
        const $ = cheerio.load(html);
        const dl = $("dl").first();
        const dt = dl.children("dt").eq(0);
        return this.getChildrenNode(dt, []);
    }

    getChildrenNode = (node: Cheerio<any>, bookMarks: Array<Folder | File> = []) => {
        //下一级文件夹目录列表
        const childrenNodeDL = node.children("dl");
        const childrenNodeDT = childrenNodeDL.children("dt");
        const dir = this.getNodeTitle(node);
        dir.children = [];
        !!dir.title && bookMarks.push(dir) && (dir.id = `${this.count++}`);
        childrenNodeDT.map((i) => {
            const info = this.getNodeTitle(childrenNodeDT.eq(i));
            !!!info.title && dir.children.push(info) && (info.id = `${this.count++}`);
            this.getChildrenNode(childrenNodeDT.eq(i), dir.children);
        });
        return bookMarks;
    };
    getNodeTitle = (node: Cheerio<any>) => {
        let info: any = {};
        const title = node.children("h3");
        // 如果h3的length为0则不是文件夹，就获取网站名称和网址，否则是文件夹并赋值title
        title.length === 0 && this.getNodeInfo(node, info) ||
            (info.title = title.text())
        return info;
    };
    getNodeInfo = (node: Cheerio<any>, info: any) => {
        info.name = node.children("a").text();
        info.href = node.children("a").attr("href");
        info.icon = node.children("a").attr("icon");
        return info;
    };
}